package com.example.order.controller;

import com.example.order.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author zhuyaotong
 * @date 2021/6/2
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 注入 DiscoveryClient
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 参数：商品 ID
     * 通过订单系统，调用商品服务根据 ID 查询商品信息
     * 1. 需要配置商品对象
     * 2. 需要调用商品服务
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/buy/{id}", method = RequestMethod.GET)
    public Product findById(@PathVariable Long id) {

        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);

        Product product = null;

        // 如何调用商品服务？
        product = restTemplate.getForObject("http://" + instance.getHost() + ":" +  instance.getPort() + "/product/" + id, Product.class);

        return product;
    }

}
